<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    :title="title"
    :type="type"
    :visible.sync="isVisible"
    :width="width"
    top="50px"
  >
    <el-form ref="form" :model="user" :rules="rules" label-position="right" label-width="100px">
      <el-form-item label="线路编号" prop="lineNumber">
        <el-input v-model="user.lineNumber" placeholder="请输入线路编号" />
      </el-form-item>
      <el-form-item label="线路名称" prop="name">
        <el-input v-model="user.name" placeholder="请输入线路名称" />
      </el-form-item>
      <el-form-item label="线路类型" prop="transportLineType">
        <el-select v-model="user.transportLineTyp" clearable placeholder="请选择线路类型">
          <el-option
            v-for="item in orgListXL"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="起始地结构" prop="orgId">
        <treeselect
          v-model="user.orgId"
          :clear-value-text="$t('common.clear')"
          :load-options="loadListOptions"
          :multiple="false"
          :options="orgList"
          :searchable="true"
          placeholder=" "
          style="width:100%"
        />
      </el-form-item>
      <el-form-item label="目的地机构" prop="orgId">
        <treeselect
          v-model="user.orgId"
          :clear-value-text="$t('common.clear')"
          :load-options="loadListOptions"
          :multiple="false"
          :options="orgList"
          :searchable="true"
          placeholder=" "
          style="width:100%"
        />
      </el-form-item>
      <el-form-item label="距离" prop="distance">
        <el-input v-model="user.distance" placeholder="请输入距离" />
      </el-form-item>
      <el-form-item label="成本" prop="cost">
        <el-input v-model="user.cost" placeholder="请输入成本" />
      </el-form-item>
      <el-form-item label="预计时间" prop="estimatedTime">
        <el-input v-model="user.estimatedTime" placeholder="请输入预计时间" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="isVisible = false">{{ $t('common.cancel') }}</el-button>
      <el-button plain type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>
<script>

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import transportLine from '@/api/transportLine.js'

export default {
  name: 'UserEdit',
  components: { Treeselect },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      orgListXL: [],
      remoteStationLoading: false,
      user: this.initUser(),
      screenWidth: 0,
      width: this.initWidth(),
      orgList: [],
      stationList: [],
      imgFileList: [],
      imgFileData: {
        bizId: '',
        bizType: 'USER_AVATAR'
      },
      // 图片文件总数
      imgFileTotal: 0,
      // 上传成功数
      successNum: 0,
     rules: {
        typeNumbers: [
          {
            required: true,
            message: "请输入车型名称",
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: this.$t('rules.range4to10'),
            trigger: 'blur'
          },
        ],
        goods: [
          {
            required: true,
            message: "请选择适用货品",
            trigger: 'blur'
          },
        ]
      }
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.close()
        this.reset()
      }
    },
    enums() {
      return this.$store.state.common.enums
    },
    title() {
      return this.type === 'add'
        ? this.$t('common.add')
        : this.$t('common.edit')
    }
  },
  watch: {
    // 监听deptId
    'user.orgId': 'orgSelect'
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.width = this.initWidth()
      })()
    }
  },
  methods: {
    myAvatar(avatar) {
      if (!avatar) {
        return require(`@/assets/avatar/default.jpg`)
      } else {
        if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
          return avatar
        } else {
          return require(`@/assets/avatar/${avatar}`)
        }
      }
    },
    initUser() {
      return {
     orgId: null,
      }
    },
    initWidth() {
      this.screenWidth = document.body.clientWidth
      if (this.screenWidth < 991) {
        return '90%'
      } else if (this.screenWidth < 1400) {
        return '45%'
      } else {
        return '800px'
      }
    },

    loadListOptions({ callback }) {
      callback()
    },
    orgSelect(node) {
      this.loadStation(node)
    },
    loadStation(orgId) {
      if (orgId) {
        transportLine.page({ orgId: orgId, status: true }).then(response => {
          const res = response.data
          this.stationList = res.data.records
        })
      } else {
        this.stationList = []
      }
    },
    // setIdAndSubmit(bizId, url) {
    //   const vm = this
    //   vm.successNum += 1
    //   vm.imgFileData.bizId = bizId
    //   vm.user.avatar = url
    //   vm.user.id = bizId

    //   if (vm.successNum === vm.imgFileTotal) {
    //     vm.$store.state.hasLoading = false
    //   }
    // },
    setUser(val, orgs,orgListXL) {
      const vm = this
      if (val) {
        vm.user = { ...val }
      }
      vm.orgList = orgs
      vm.imgFileData.bizId = vm.user['id']
      vm.orgListXL =orgListXL
      // vm.$nextTick(() => {
      //   vm.$refs.imgFileRef.init({
      //     bizId: vm.user['id'],
      //     bizType: vm.imgFileData.bizType,
      //     imageUrl: vm.myAvatar(vm.user['avatar']),
      //     isSingle: true,
      //     isDetail: false
      //   })
      // })
    },
    close() {
      this.$emit('close')
    },
    reset() {
      // 先清除校验，再清除表单，不然有奇怪的bug
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.user = this.initUser()
      // this.imgFileData.bizId = ''
      // this.$refs.imgFileRef.init({
      //   bizId: '',
      //   bizType: '',
      //   imageUrl: '',
      //   isSingle: true,
      //   isDetail: false
      // })
    },
    submitForm() {
      const vm = this
      this.$refs.form.validate(valid => {
        if (valid) {
          vm.editSubmit()
        } else {
          return false
        }
      })
    },
    editSubmit() {
      const vm = this
      if (vm.type === 'add') {
        vm.save()
      } else {
        vm.update()
      }
    },
    save() {
      const vm = this
      console.log(this.user)
      transportLine.save(this.user).then(response => {
        const res = response.data
        if (res) {
          vm.isVisible = false
          vm.$message({
            message: vm.$t('tips.createSuccess'),
            type: 'success'
          })
          vm.$emit('success')
        }
      })
    },
    update() {
      
      transportLine.update(this.user).then(response => {
        const res = response.data
        if (res) {
          this.isVisible = false
          this.$message({
            message: this.$t('tips.updateSuccess'),
            type: 'success'
          })
          this.$emit('success')
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
